package com.liaoye.hellocustomview.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class PathGetSegmentView extends View {


    private Paint paint;
    private Path path;
    private final String TAG = PathGetSegmentView.class.getSimpleName();
    private Path dst;
    private PathMeasure pathMeasure;
    private float animatedValue;

    public PathGetSegmentView(Context context) {
        super(context);
        init();
    }

    public PathGetSegmentView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        //设置画笔的基本属性
        paint = new Paint();
        //设置画笔颜色
        paint.setColor(Color.RED);
        //设置填充样式
        paint.setStyle(Paint.Style.STROKE);
        //设置画笔宽度
        paint.setStrokeWidth(5);

        path = new Path();
        pathMeasure = new PathMeasure();
        dst = new Path();


        path.addCircle(0,0, 100, Path.Direction.CW);

        pathMeasure.setPath(path, false);




        ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.addUpdateListener(animation -> {
            animatedValue = (float) animator.getAnimatedValue();
            invalidate();
        });
        animator.setDuration(2000);
        animator.start();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(200, 200);

        dst.reset();
        float length = pathMeasure.getLength();
        float start = 0;
        float stop = animatedValue * length;
        start = (float) (stop - (0.5 - Math.abs(animatedValue - 0.5)) * length);
        pathMeasure.getSegment(start, stop, dst, true);
        canvas.drawPath(dst, paint);
    }
}
